package mock;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DefaultDao implements IDao {

	@Override
	public boolean exists(String orderNum) {
		boolean st = false;
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {

			Class.forName("org.sqlite.JDBC");

			// creating connection with the database
			con = DriverManager
					.getConnection("jdbc:sqlite:/d:/work/eclipse-luna/workspace20160305/demo-jspservlet/j2ee.db");
			ps = con.prepareStatement("select * from orders where orderNum=?");
			ps.setString(1, orderNum);

			rs = ps.executeQuery();
			st = rs.first();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null)
					rs.close();
				if (ps != null)
					ps.close();
				if (con != null)
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return st;
	}

	@Override
	public Order getOrder(String orderNum) {
		boolean st = false;
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		Order o = null;
		try {

			Class.forName("org.sqlite.JDBC");

			// creating connection with the database
			con = DriverManager
					.getConnection("jdbc:sqlite:/d:/work/eclipse-luna/workspace20160305/demo-jspservlet/j2ee.db");
			ps = con.prepareStatement("select * from orders where orderNum=?");
			ps.setString(1, orderNum);

			rs = ps.executeQuery();
			st = rs.first();
			if (st == true) {
				int goodsCount = rs.getInt("count");
				int payment = rs.getInt("payment");
				o = new Order(orderNum, goodsCount, payment);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null)
					rs.close();
				if (ps != null)
					ps.close();
				if (con != null)
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return o;

	}

}
